import memoizeOne from 'memoize-one';
import isEqual from 'lodash/isEqual';
import { formatMessage } from 'umi-plugin-react/locale';
import Authorized from '@/utils/Authorized';
import router from 'umi/router';
import { menu } from '../defaultSettings';
import { deleteCollection, addCollection, getCollection } from '@/services/api';
import { getFundTwoStockPosition } from '../services/allposition2_service';
import { getGeneratePosition } from '../services/allposition_service';
import { Button, Card, Divider, Form, message, Modal, notification } from 'antd';

const { check } = Authorized;

// Conversion router to menu.
function formatter(data, parentAuthority, parentName) {
  if (!data) {
    return undefined;
  }
  return data
    .map(item => {
      if (!item.name || !item.path) {
        return null;
      }

      let locale = 'menu';
      if (parentName && parentName !== '/') {
        locale = `${parentName}.${item.name}`;
      } else {
        locale = `menu.${item.name}`;
      }
      // if enableMenuLocale use item.name,
      // close menu international
      const name = menu.disableLocal
        ? item.name
        : formatMessage({ id: locale, defaultMessage: item.name });
      const result = {
        ...item,
        name,
        locale,
        authority: item.authority || parentAuthority,
      };
      if (item.routes) {
        const children = formatter(item.routes, item.authority, locale);
        // Reduce memory usage
        result.children = children;
      }
      delete result.routes;
      return result;
    })
    .filter(item => item);
}

const memoizeOneFormatter = memoizeOne(formatter, isEqual);

/**
 * get SubMenu or Item
 */
const getSubMenu = item => {
  // doc: add hideChildrenInMenu
  if (item.children && !item.hideChildrenInMenu && item.children.some(child => child.name)) {
    return {
      ...item,
      children: filterMenuData(item.children), // eslint-disable-line
    };
  }
  return item;
};

/**
 * filter menuData
 */
const filterMenuData = menuData => {
  if (!menuData) {
    return [];
  }
  return menuData
    .filter(item => item.name && !item.hideInMenu)
    .map(item => check(item.authority, getSubMenu(item)))
    .filter(item => item);
};
/**
 * 获取面包屑映射
 * @param {Object} menuData 菜单配置
 */
const getBreadcrumbNameMap = menuData => {
  if (!menuData) {
    return {};
  }
  const routerMap = {};

  const flattenMenuData = data => {
    data.forEach(menuItem => {
      if (menuItem.children) {
        flattenMenuData(menuItem.children);
      }
      // Reduce memory usage
      routerMap[menuItem.path] = menuItem;
    });
  };
  flattenMenuData(menuData);
  return routerMap;
};

const memoizeOneGetBreadcrumbNameMap = memoizeOne(getBreadcrumbNameMap, isEqual);

export default {
  namespace: 'menu',

  state: {
    menuData: [],
    routerData: [],
    breadcrumbNameMap: {},
    collection:[],
  },

  effects: {
    *addCollection({ payload, callback }, { call, put }) {
      const response = yield call(addCollection, payload);
      if (typeof response === 'undefined') {
        return;
      }
      if (typeof response !== 'undefined' && response.code === 1) {
        message.success(response.message);
        if (callback) callback(response);
        // yield put({
        //   type: 'saveCollection',
        //   payload
        // });
      } else {
        notification.error({
          message: typeof response.message !== 'undefined' ? response.message : '请求错误',
        });
      }
    },
      *deleteCollection({ payload, callback }, { call, put }) {
      const response = yield call(deleteCollection, payload);
      if (typeof response === 'undefined') {
        return;
      }
      if (typeof response !== 'undefined' && response.code === 1) {
        message.success(response.message);
        if (callback) callback(response);
        // yield put({
        //   type: 'saveCollection',
        //   payload
        // });
      } else {
        notification.error({
          message: typeof response.message !== 'undefined' ? response.message : '请求错误',
        });
      }
    },
    *getCollection({ payload, callback }, { call, put }) {
      const response = yield call(getCollection, payload);
      if (typeof response === 'undefined') {
        return;
      }
      if (typeof response !== 'undefined' && response.code === 1) {
        if (callback) callback(response);
        yield put({
          type: 'saveCollection',
          payload:response.list
        });
      } else {
        notification.error({
          message: typeof response.message !== 'undefined' ? response.message : '请求错误',
        });
      }
    },

    *getMenuData({ payload }, { put }) {
      const { routes, authority, path } = payload;
      const originalMenuData = memoizeOneFormatter(routes, authority, path);
      const menuData = filterMenuData(originalMenuData);
      const breadcrumbNameMap = memoizeOneGetBreadcrumbNameMap(originalMenuData);

      let menuDatas = [];
      if (typeof window.reloadFlag !== 'undefined' && window.reloadFlag === 1) {
        window.reloadFlag = 2;
        const s = JSON.stringify(menuData);
        localStorage.setItem('tg-link1', s);
        menuDatas = menuData;
      } else if (typeof window.reloadFlag === 'undefined') {
        const v = localStorage.getItem('antd-pro-authority');
        if (v === null) {
          menuDatas = menuData;
          return false;
        }
        const sTemp = v.substring(1, v.length - 1);
        const sArray = sTemp.split(',');
        for (let i = 0; i < sArray.length; i++) {
          if (sArray[i] !== '"guest"') {
            window.reloadFlag = 2;
            const p = localStorage.getItem('tg-link1');
            if (p === null) {
              const s = JSON.stringify(menuData);
              localStorage.setItem('tg-link1', s);
              menuDatas = menuData;
            } else {
              const sArrayp = JSON.parse(p);
              menuDatas = sArrayp;
            }
          } else {
            menuDatas = menuData;
            break;
          }
        }
      } else {
        menuDatas = menuData;
      }

      let breadcrumbNameMaps = [];
      if (typeof window.reloadFlag !== 'undefined' && window.reloadFlag === 1) {
        window.reloadFlag = 2;
        const s = JSON.stringify(breadcrumbNameMap);
        localStorage.setItem('tg-link3', s);
        breadcrumbNameMaps = breadcrumbNameMap;
      } else if (typeof window.reloadFlag === 'undefined') {
        const v = localStorage.getItem('antd-pro-authority');
        if (v === null) {
          breadcrumbNameMaps = breadcrumbNameMap;
          return false;
        }
        const sTemp = v.substring(1, v.length - 1);
        const sArray = sTemp.split(',');
        for (let i = 0; i < sArray.length; i++) {
          if (sArray[i] !== '"guest"') {
            window.reloadFlag = 2;
            const p = localStorage.getItem('tg-link2');
            if (p === null) {
              const s = JSON.stringify(breadcrumbNameMap);
              localStorage.setItem('tg-link2', s);
              breadcrumbNameMaps = breadcrumbNameMap;
            } else {
              const sArrayp = JSON.parse(p);
              breadcrumbNameMaps = sArrayp;
            }
          } else {
            breadcrumbNameMaps = breadcrumbNameMap;
            break;
          }
        }
      } else {
        breadcrumbNameMaps = breadcrumbNameMap;
      }

      let routess = [];
      if (typeof window.reloadFlag !== 'undefined' && window.reloadFlag === 1) {
        window.reloadFlag = 2;
        const s = JSON.stringify(routes);
        localStorage.setItem('tg-link3', s);
        routess = routes;
      } else if (typeof window.reloadFlag === 'undefined') {
        const v = localStorage.getItem('antd-pro-authority');
        if (v === null) {
          routess = routes;
          return false;
        }
        const sTemp = v.substring(1, v.length - 1);
        const sArray = sTemp.split(',');
        for (let i = 0; i < sArray.length; i++) {
          if (sArray[i] !== '"guest"') {
            window.reloadFlag = 2;
            const p = localStorage.getItem('tg-link3');
            if (p === null) {
              const s = JSON.stringify(routes);
              localStorage.setItem('tg-link3', s);
              routess = routes;
            } else {
              const sArrayp = JSON.parse(p);
              routess = sArrayp;
            }
          } else {
            routess = routes;
            break;
          }
        }
      } else {
        routess = routes;
      }

      yield put({
        type: 'save',
        payload: {
          menuData: menuDatas,
          breadcrumbNameMap: breadcrumbNameMaps,
          routerData: routess,
        },
      });
    },
    *authRoutes({ payload }, { call }) {
      // const response = yield call(accountLogin, payload);if(typeof(response)==='undefined'){return;}
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
   saveCollection(state, action) {
      return {
        ...state,
       collection:action.payload,
      };
    },
  },
};
